package com.visionblue.business.ship.page.collection.panel.flow

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.visionblue.business.ship.R
import com.visionblue.business.ship.base.BaseFragment
import com.visionblue.business.ship.model.bean.local.OilFlowInfo
import com.visionblue.business.ship.model.bean.local.UltraSonicFlowInfo
import com.visionblue.business.ship.model.bean.local.WaterFlowInfo
import com.visionblue.business.ship.model.bean.response.ApplicationDetail
import com.visionblue.business.ship.model.enums.WasteTypeEnum
import com.visionblue.business.ship.model.repository.db.MeasureMenuItem
import com.visionblue.business.ship.page.collection.CollectionActivity
import com.visionblue.business.ship.page.collection.CollectionViewModel
import com.visionblue.business.ship.page.outer.OuterActivity
import com.visionblue.business.ship.util.toast
import kotlinx.android.synthetic.main.frag_flow_child.*
import org.koin.androidx.viewmodel.ext.android.sharedViewModel

/**
 * @author: xlh
 * @date: 2020-05-20 5:07 PM
 * @desc:  可划分为三种状态：
 *          未开始工作前（BeforeWorkFlowFragment，将输油管工作前和输水管工作前两个状态合并） 输油管在工作（OilFlowFragment）
 *          输水管在工作（WaterFlowFragment）
 */
class FlowChildFragment : BaseFragment() {

    private val mViewModel: CollectionViewModel by sharedViewModel()

    private val mFlowListAdapter = FlowListAdapter()

    override val layoutId: Int = R.layout.frag_flow_child

    override fun initView(savedInstanceState: Bundle?) {

        flowListView.layoutManager = LinearLayoutManager(context)
        flowListView.adapter = mFlowListAdapter
        mFlowListAdapter.onStateChangeListener = object : FlowListAdapter.OnStateChangeListener {
            override fun onIsContainListener(type: String): Boolean {
                var flagContain =false
                val collectionActivity:CollectionActivity = activity as CollectionActivity;
                val applicationDetail: ApplicationDetail? = collectionActivity.applicationDetail

                if(applicationDetail?.applicationItems==null){
                    if(isOutput()==true){
                        toast { "请先确定选择转出对象" }
                    }else{
                        toast { "请先确定选择接收对象" }
                    }

                }else{
                    for (data in applicationDetail?.applicationItems!!){
                        if (data.wasteType == type){
                            flagContain = true
                        }
                    }
                }


                return if (flagContain){
                    true
                }else{
                    Toast.makeText(
                            activity,
                            "接收申报单不含有此项无法添加",
                            Toast.LENGTH_SHORT
                    ).show()
                    false
                }

            }

            override fun onWatchStart(
                measureMenuItem: MeasureMenuItem,
                wasteTypeEnum: WasteTypeEnum
            ) {
                when {
                    //废水
                    measureMenuItem.isWasteWater()-> mViewModel.startWatchWasteWaterPipeInfo(
                        measureMenuItem,
                        isOutput(),
                        wasteTypeEnum
                    )
                    measureMenuItem.isWater() -> mViewModel.startWatchWaterPipeInfo(
                        measureMenuItem,
                        isOutput(),
                        wasteTypeEnum
                    )
                    measureMenuItem.isOil() -> mViewModel.startWatchOilPipeInfo(
                        measureMenuItem,
                        isOutput(),
                        wasteTypeEnum
                    )
                    measureMenuItem.isUltraSonic() -> mViewModel.startWatchUltraSonicInfo(
                        measureMenuItem,
                        isOutput(),
                        wasteTypeEnum
                    )
                }

            }

            override fun onWatchStop(measureMenuItem: MeasureMenuItem) {
                val isOutput = isOutput() ?: return
                when {
                    measureMenuItem.isWater() -> mViewModel.stopWatchWaterPipeInfo(isOutput)
                    measureMenuItem.isWasteWater() -> mViewModel.stopWatchWasteWaterPipeInfo(isOutput)
                    measureMenuItem.isOil() -> mViewModel.stopWatchOilPipeInfo(isOutput)
                    measureMenuItem.isUltraSonic() -> mViewModel.stopWatchUltraSonicInfo(isOutput)
                }
            }
        }
//        flowWater.onSwitchClickListener = object : FlowViewLayout.OnSwitchClickListener() {
//            override fun onStart() {
//                showWaterSelectionDialog()
//            }
//
//            override fun onStop() {
//                mViewModel.stopWatchWaterPipeInfo()
//            }
//        }
//
//        flowOil.onSwitchClickListener = object : FlowViewLayout.OnSwitchClickListener() {
//            override fun onStart() {
//                showOilSelectionDialog()
//            }
//
//            override fun onStop() {
//                mViewModel.stopWatchOilPipeInfo()
//            }
//        }

//        if (savedInstanceState == null) {
//
//
//            // 默认进入页面后两个流量计开始计量
//        }
    }

//    private fun showOilSelectionDialog() {
//        SelectionDialog(
//            context!!, listOf(
//                // 含油污水
//                SelectionItem(WasteTypeEnum.OIL_WASTE.desc, {
//                    flowOil.showWorking()
//                    mViewModel.startWatchOilPipeInfo(isOutput(), WasteTypeEnum.OIL_WASTE)
//                }),
//                // 残油
//                SelectionItem(WasteTypeEnum.RESIDUAL_OIL.desc, {
//                    flowOil.showWorking()
//                    mViewModel.startWatchOilPipeInfo(
//                        isOutput(),
//                        WasteTypeEnum.RESIDUAL_OIL
//                    )
//                })
//            )
//        ).show()
//    }
//
//    private fun showWaterSelectionDialog() {
//        SelectionDialog(
//            context!!, listOf(
//                // 生活污水
//                SelectionItem(WasteTypeEnum.LIFE_WASTE.desc, {
//                    flowWater.showWorking()
//                    mViewModel.startWatchWaterPipeInfo(isOutput(), WasteTypeEnum.LIFE_WASTE)
//                }),
//                // 含有毒液体物质的污水
//                SelectionItem(WasteTypeEnum.HAZARDOUS_WASTE.desc, {
//                    flowWater.showWorking()
//                    mViewModel.startWatchWaterPipeInfo(
//                        isOutput(),
//                        WasteTypeEnum.HAZARDOUS_WASTE
//                    )
//                })
//            )
//        ).show()
//    }


    override fun initData() {
        super.initData()

        mViewModel.oilFlowInfoLiveData.observe(this, Observer { onOilInfoUpdate(it) })
        mViewModel.waterFlowInfoLiveData.observe(this, Observer { onWaterInfoUpdate(it) })
        mViewModel.wasteWaterFlowInfoLiveData.observe(this, Observer { onWasteWaterInfoUpdate(it) })
        mViewModel.sonicInfoLiveData.observe(this, Observer { onUltraSonicUpdate(it) })
        mViewModel.inCheckMode.observe(this, Observer {
//            if (it) {
//                flowOil.showDisable()
//                flowWater.showDisable()
//            } else {
//                flowWater.showIdle()
//                flowOil.showIdle()
//            }
            if (it) {
                mFlowListAdapter.setAllDisable()
            } else {
                mFlowListAdapter.setAllIdle()
            }

        })

        mViewModel.menuItemsLiveData.observe(this, Observer { menuItems ->
//            flowOil.setVisible(false)
//            flowWater.setVisible(false)
            val flowItems = menuItems.filter { it.isFlow() }

            flowItems.forEach {
                if (it.isWater()) {
//                    flowWater.setTypeText(it.alias.toString())
//                    flowWater.showWorking()
//                    flowWater.setVisible(true)
                    mViewModel.startWatchWaterPipeInfo(it, isOutput(), WasteTypeEnum.WATER_UNDEFINE)
                }
                if (it.isWasteWater()) {
//                    flowWater.setTypeText(it.alias.toString())
//                    flowWater.showWorking()
//                    flowWater.setVisible(true)
                    mViewModel.startWatchWasteWaterPipeInfo(it, isOutput(), WasteTypeEnum.WASTE_WATER_UNDEFINE)
                }

                if (it.isOil()) {
//                    flowOil.setTypeText(it.alias.toString())
//                    flowOil.showWorking()
//                    flowOil.setVisible(true)
                    mViewModel.startWatchOilPipeInfo(it, isOutput(), WasteTypeEnum.OIL_UNDEFINE)
                }

                if (it.isUltraSonic()) {
                    mViewModel.startWatchUltraSonicInfo(
                        it,
                        isOutput(),
                        WasteTypeEnum.ULTRA_UNDEFINE
                    )
                }
            }
            mFlowListAdapter.setData(flowItems)
        })
//        mViewModel.currWorkStatusLiveData.observe(this, Observer {
//            when (it) {
//                WorkStatus.BEFORE_WORK -> {
//                    mViewModel.stopWatchOilPipeInfo()
//                    mViewModel.stopWatchWaterPipeInfo()
//                }
//                WorkStatus.WORKING -> {
//                    val isOutput = when (activity) {
//                        is CollectionActivity -> {
//                            (activity as CollectionActivity).isOutput()
//                        }
//                        is OuterActivity -> {
//                            (activity as OuterActivity).isOutput()
//                        }
//                        else -> {
//                            null
//                        }
//                    }
//                    mViewModel.checkFlowType(
//                        oil = mViewModel::startWatchOilPipeInfo,
//                        water = mViewModel::startWatchWaterPipeInfo
//                    )?.invoke(isOutput)
//                }
////                WorkStatus.FINISHED -> {
////                    mViewModel.stopWatchOilPipeInfo()
////                    mViewModel.stopWatchWaterPipeInfo()
////                }
//                else -> {
//
//                }
//            }
//        })

    }

    private fun onOilInfoUpdate(oilFlowInfo: OilFlowInfo) {
//        flowOil.showWorking(
//            volume = "${FormatUtils.format3Decimal(oilFlowInfo.positiveAccumulationVal)} m³",
//            speed = "${FormatUtils.format3Decimal(oilFlowInfo.instantFlowRate)} m³/h"
//        )
        mFlowListAdapter.updateOil(oilFlowInfo)
    }

    private fun onWaterInfoUpdate(waterFlowInfo: WaterFlowInfo) {
//        flowWater.showWorking(
//            volume = "${FormatUtils.format3Decimal(waterFlowInfo.positiveAccumulationVal)} m³",
//            speed = "${FormatUtils.format3Decimal(waterFlowInfo.instantFlowRate)} m³/h"
//        )
        Log.e("--->",waterFlowInfo.toString()+"wwwww")
        mFlowListAdapter.updateWater(waterFlowInfo)
    }

    private fun onWasteWaterInfoUpdate(waterFlowInfo: WaterFlowInfo) {
//        flowWater.showWorking(
//            volume = "${FormatUtils.format3Decimal(waterFlowInfo.positiveAccumulationVal)} m³",
//            speed = "${FormatUtils.format3Decimal(waterFlowInfo.instantFlowRate)} m³/h"
//        )
        mFlowListAdapter.updateWasteWater(waterFlowInfo)
    }

    private fun onUltraSonicUpdate(ultraSonicFlowInfo: UltraSonicFlowInfo) {
        mFlowListAdapter.updateSonic(ultraSonicFlowInfo)
    }


    private fun isOutput(): Boolean? {
        return when (activity) {
            is CollectionActivity -> {
                (activity as CollectionActivity).isOutput()
            }
            is OuterActivity -> {
                (activity as OuterActivity).isOutput()
            }
            else -> {
                null
            }
        }
    }

//    override fun onSaveInstanceState(outState: Bundle) {
//        super.onSaveInstanceState(outState)
//        outState.putInt(WATER_PIPE_STATE, flowWater.getCurrState())
//        outState.putInt(OIL_PIPE_STATE, flowOil.getCurrState())
//    }
//
//    override fun onViewStateRestored(savedInstanceState: Bundle?) {
//        super.onViewStateRestored(savedInstanceState)
//        savedInstanceState?.run {
//            flowOil?.setState(getInt(OIL_PIPE_STATE))
//            flowWater?.setState(getInt(WATER_PIPE_STATE))
//        }
//    }

    companion object {
//        private const val WATER_PIPE_STATE = "waterPipe"
//        private const val OIL_PIPE_STATE = "oilPipe"

        fun newInstance(): FlowChildFragment {
            return FlowChildFragment()
        }
    }
}